package com.apache.client.protocol;

import java.io.InputStream;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.apache.api.vo.ResultEntity;
import com.apache.attachment.mommon.ToolsUtil;
import com.apache.attachment.mommon.XmlUtil;

public class HttpProtocolService extends AbstractProtocolClient {

	private Logger logger = Logger.getLogger(HttpProtocolService.class);
	private String keyFix = "attachment/service/doService.action";
	private String proKey = "atta_server";

	public HttpProtocolService() {
	}

	public HttpProtocolService(String keyFix, String proKey) {
		this.keyFix = keyFix;
		this.proKey = proKey;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 */
	public ResultEntity doService(String beanId, String methodKey, Map<String, Object> params) {
		String xmlParams = this.buildXml(beanId, methodKey, "XML", params);
		ResultEntity resultEntity = null;
		String httpUrl = ToolsUtil.getInstance().getValueByKey(proKey) + keyFix;
		try {
			String result = postHttp(httpUrl, xmlParams, "XML");
			if (ToolsUtil.isNull(result)) {
				resultEntity = getResultEntity("接口调用超时");
				return resultEntity;
			}
			resultEntity = XmlUtil.toBean(result, ResultEntity.class);
		} catch (Exception e) {
			resultEntity = getResultEntity(e.getMessage());
		}
		return resultEntity;
	}

	/**
	 * post http 请求，接受返回的结果xml文档	 
	 * @param url webservice地址
	 * @param parasInput 传递的参数
	 * @return xml类型字符串
	 */
	private String postHttp(String url, String params, String type) {
		StringBuilder sb = new StringBuilder();
		PostMethod postMethod = new PostMethod(url);
		try {
			//重新构造参数数组，是为了加入公共参数：随机数，以防缓存影响执行结果				
			NameValuePair[] paras = new NameValuePair[3];
			paras[0] = new NameValuePair("httpRand", "" + System.currentTimeMillis());
			paras[1] = new NameValuePair("params", "" + params);
			paras[2] = new NameValuePair("ParamType", "" + type);

			HttpClient client = new HttpClient();
			client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			postMethod.setRequestBody(paras);//绑定参数
			logger.info("HTTP请求发送成功");
			int statusCode = client.executeMethod(postMethod);
			logger.info("服务端返回请求状态，状态码为：" + statusCode);
			if (statusCode == HttpStatus.SC_OK) {//如果执行成功
				InputStream inputStream = postMethod.getResponseBodyAsStream();
				String line = IOUtils.toString(inputStream, "UTF-8");
				inputStream.close();
				return line;
			} else {
				logger.error("HTTP请求响应失败，错误码为：" + statusCode);
			}
		} catch (Exception e) {
			logger.error(e);
		} finally {
			postMethod.releaseConnection();//释放连接
		}
		return sb.toString();
	}
}
